package com.heyige.facade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heyige.dto.MemberDto;
import com.heyige.entity.MemberLevel;
import com.heyige.entity.MemberOrder;
import com.heyige.entity.User;
import com.heyige.entity.UserQuota;
import com.heyige.exception.BusinessException;
import com.heyige.exception.ErrorCode;
import com.heyige.service.MemberLevelService;
import com.heyige.service.MemberOrderService;
import com.heyige.service.UserQuotaService;
import com.heyige.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberFacade {

    private final MemberLevelService memberLevelService;

    private final MemberOrderService memberOrderService;

    private final UserService userService;

    private final UserQuotaService userQuotaService;

    /**
     * 获取所有会员等级
     *
     * @param page   分页参数
     * @param size   分页参数
     * @return 会员等级列表
     */
    public Page<MemberLevel> getAllMemberLevels(Integer page, Integer size) {
        Page<MemberLevel> pageObj = new Page<>(page, size);
        LambdaQueryWrapper<MemberLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberLevel::getIsActive, true)
                .orderByAsc(MemberLevel::getSortOrder);
        return memberLevelService.page(pageObj, queryWrapper);
    }

    /**
     * 获取会员等级详情
     *
     * @param id 会员等级ID
     * @return 会员等级详情
     */
    public MemberLevel getMemberLevel(Long id) {
        LambdaQueryWrapper<MemberLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberLevel::getId, id)
                .eq(MemberLevel::getIsActive, true);
        return memberLevelService.getOne(queryWrapper);
    }

    /**
     * 创建会员订单
     *
     * @param userId  用户ID
     * @param request 创建订单请求
     * @return 订单响应
     */
    @Transactional
    public MemberDto.OrderResponse createMemberOrder(Long userId, MemberDto.CreateOrderRequest request) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
        }

        // 检查会员等级是否存在
        LambdaQueryWrapper<MemberLevel> levelQueryWrapper = new LambdaQueryWrapper<>();
        levelQueryWrapper.eq(MemberLevel::getId, request.getMemberLevelId())
                .eq(MemberLevel::getIsActive, true);
        MemberLevel memberLevel = memberLevelService.getOne(levelQueryWrapper);
        if (memberLevel == null) {
            throw new BusinessException(ErrorCode.MEMBER_LEVEL_NOT_FOUND, "会员等级不存在");
        }

        // 生成订单号
        String orderNo = generateOrderNo();

        // 创建订单
        MemberOrder order = new MemberOrder();
        order.setUserId(userId);
        order.setMemberLevelId(request.getMemberLevelId());
        order.setOrderNo(orderNo);
        order.setAmount(memberLevel.getPrice());
        order.setDurationDays(memberLevel.getDurationDays());
        order.setStatus(MemberOrder.OrderStatus.PENDING.name());

        memberOrderService.save(order);

        // 构建响应
        return buildOrderResponse(order, memberLevel);
    }

    /**
     * 支付会员订单
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     * @param request 支付请求
     * @return 订单响应
     */
    @Transactional
    public MemberDto.OrderResponse payMemberOrder(Long orderId, Long userId, MemberDto.PayRequest request) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<MemberOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(MemberOrder::getId, orderId)
                .eq(MemberOrder::getUserId, userId);
        MemberOrder order = memberOrderService.getOne(orderQueryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 检查订单状态
        if (!order.getStatus().equals(MemberOrder.OrderStatus.PENDING.name())) {
            throw new BusinessException(ErrorCode.ORDER_ALREADY_PAID, "订单状态不正确");
        }

        // 获取会员等级信息
        LambdaQueryWrapper<MemberLevel> levelQueryWrapper = new LambdaQueryWrapper<>();
        levelQueryWrapper.eq(MemberLevel::getId, order.getMemberLevelId())
                .eq(MemberLevel::getIsActive, true);
        MemberLevel memberLevel = memberLevelService.getOne(levelQueryWrapper);
        if (memberLevel == null) {
            throw new BusinessException(ErrorCode.MEMBER_LEVEL_NOT_FOUND, "会员等级不存在");
        }

        // 更新订单状态
        order.setStatus(MemberOrder.OrderStatus.PAID.name());
        order.setPaymentMethod(request.getPaymentMethod());
        order.setPaymentNo(request.getPaymentNo());
        order.setPaidTime(LocalDateTime.now());

        // 计算会员时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now;
        LocalDateTime endTime = now.plusDays(order.getDurationDays());

        // 如果用户已经是VIP，则延长会员时间
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
        }

        if (user.getIsVip() && user.getVipExpireTime() != null && user.getVipExpireTime().isAfter(now)) {
            startTime = user.getVipExpireTime();
            endTime = startTime.plusDays(order.getDurationDays());
        }

        order.setStartTime(startTime);
        order.setEndTime(endTime);

        memberOrderService.updateById(order);

        // 更新用户VIP状态
        user.setIsVip(true);
        user.setVipExpireTime(endTime);
        userService.updateById(user);

        // 更新用户配额
        LambdaQueryWrapper<UserQuota> quotaQueryWrapper = new LambdaQueryWrapper<>();
        quotaQueryWrapper.eq(UserQuota::getUserId, userId);
        UserQuota userQuota = userQuotaService.getOne(quotaQueryWrapper);
        if (userQuota == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户配额信息不存在");
        }

        // 设置每日配额为会员等级的配额
        userQuota.setTotalQuota(memberLevel.getQuotaPerDay());
        userQuota.setRemainingQuota(memberLevel.getQuotaPerDay());
        userQuotaService.updateById(userQuota);

        log.info("用户 {} 购买会员 {}，订单 {}，会员时间从 {} 到 {}", userId, memberLevel.getName(), orderId, startTime, endTime);

        // 构建响应
        return buildOrderResponse(order, memberLevel);
    }

    /**
     * 取消会员订单
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     */
    @Transactional
    public void cancelMemberOrder(Long orderId, Long userId) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<MemberOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberOrder::getId, orderId)
                .eq(MemberOrder::getUserId, userId);
        MemberOrder order = memberOrderService.getOne(queryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 检查订单状态
        if (!order.getStatus().equals(MemberOrder.OrderStatus.PENDING.name())) {
            throw new BusinessException(ErrorCode.ORDER_CANCELLED, "订单状态不正确，无法取消");
        }

        // 更新订单状态
        order.setStatus(MemberOrder.OrderStatus.CANCELLED.name());
        order.setCancelTime(LocalDateTime.now());
        memberOrderService.updateById(order);

        log.info("用户 {} 取消会员订单 {}", userId, orderId);
    }

    /**
     * 获取用户的会员订单列表
     *
     * @param userId 用户ID
     * @param page   当前页
     * @param size   页大小
     * @return 订单列表
     */
    public Page<MemberDto.OrderResponse> getUserMemberOrders(Long userId, Integer page, Integer size) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
        }

        Page<MemberOrder> orderPage = new Page<>(page, size);
        LambdaQueryWrapper<MemberOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberOrder::getUserId, userId)
                .orderByDesc(MemberOrder::getCreatedAt);
        Page<MemberOrder> orders = memberOrderService.page(orderPage, queryWrapper);
        
        Page<MemberDto.OrderResponse> responsePage = new Page<>(page, size);
        responsePage.setTotal(orders.getTotal());
        // 这里应该将MemberOrder转换为OrderResponse，但由于缺少相关逻辑，暂时返回空页面
        return responsePage;
    }

    /**
     * 获取订单详情
     *
     * @param orderId 订单ID
     * @param userId  用户ID
     * @return 订单响应
     */
    public MemberDto.OrderResponse getMemberOrder(Long orderId, Long userId) {
        // 检查订单是否存在且属于该用户
        LambdaQueryWrapper<MemberOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(MemberOrder::getId, orderId)
                .eq(MemberOrder::getUserId, userId);
        MemberOrder order = memberOrderService.getOne(orderQueryWrapper);
        if (order == null) {
            throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在或无权限访问");
        }

        // 获取会员等级信息
        LambdaQueryWrapper<MemberLevel> levelQueryWrapper = new LambdaQueryWrapper<>();
        levelQueryWrapper.eq(MemberLevel::getId, order.getMemberLevelId())
                .eq(MemberLevel::getIsActive, true);
        MemberLevel memberLevel = memberLevelService.getOne(levelQueryWrapper);
        if (memberLevel == null) {
            throw new BusinessException(ErrorCode.MEMBER_LEVEL_NOT_FOUND, "会员等级不存在");
        }

        return buildOrderResponse(order, memberLevel);
    }

    /**
     * 检查用户VIP状态
     *
     * @param userId 用户ID
     * @return VIP状态信息
     */
    public MemberDto.VipStatusResponse checkVipStatus(Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.USER_NOT_FOUND);
        }
        
        MemberDto.VipStatusResponse response = new MemberDto.VipStatusResponse();
        response.setUserId(userId);
        response.setIsVip(user.getIsVip());

        if (user.getIsVip() && user.getVipExpireTime() != null) {
            response.setVipExpireTime(user.getVipExpireTime());

            // 计算剩余天数
            LocalDateTime now = LocalDateTime.now();
            if (user.getVipExpireTime().isAfter(now)) {
                long days = java.time.Duration.between(now, user.getVipExpireTime()).toDays();
                response.setRemainingDays((int) days);
            } else {
                response.setRemainingDays(0);
            }
        } else {
            response.setRemainingDays(0);
        }
        return response;
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        return "M" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }

    /**
     * 构建订单响应
     *
     * @param order       订单实体
     * @param memberLevel 会员等级
     * @return 订单响应
     */
    private MemberDto.OrderResponse buildOrderResponse(MemberOrder order, MemberLevel memberLevel) {
        MemberDto.OrderResponse response = new MemberDto.OrderResponse();
        response.setId(order.getId());
        response.setUserId(order.getUserId());
        response.setOrderNo(order.getOrderNo());
        response.setStatus(order.getStatus());
        response.setAmount(order.getAmount());
        response.setDurationDays(order.getDurationDays());
        response.setStartTime(order.getStartTime());
        response.setEndTime(order.getEndTime());
        response.setPaidTime(order.getPaidTime());
        response.setCreatedAt(order.getCreatedAt());

        if (memberLevel != null) {
            response.setMemberLevelId(memberLevel.getId());
            response.setMemberLevelName(memberLevel.getName());
            response.setMemberLevelDisplayName(memberLevel.getDisplayName());
        }

        return response;
    }
}